package service

import (
	"context"
	"gitee.com/cristiane/micro-mall-search-cron/model/args"
	"gitee.com/cristiane/micro-mall-search-cron/model/elasticsearch"
	"gitee.com/cristiane/micro-mall-search-cron/pkg/code"
	"gitee.com/cristiane/micro-mall-search-cron/pkg/util"
	"gitee.com/cristiane/micro-mall-search-cron/proto/micro_mall_shop_proto/shop_business"
	"gitee.com/cristiane/micro-mall-search-cron/repository"
	"gitee.com/kelvins-io/common/errcode"
	"gitee.com/kelvins-io/common/json"
	"gitee.com/kelvins-io/kelvins"
	"strconv"
)

var (
	shopSearchSyncPageSize = 50
	shopSearchSyncPageNum  = 1
)

func ShopSearchSyncTask() {
	ctx := context.Background()
	serverName := args.RpcServiceMicroMallShop
	conn, err := util.GetGrpcClient(ctx, serverName)
	if err != nil {
		kelvins.ErrLogger.Errorf(ctx, "StoreShopTask GetGrpcClient %v,err: %v", serverName, err)
		return
	}
	//defer conn.Close()
	client := shop_business.NewShopBusinessServiceClient(conn)
	count := 0
	for {
		if count > 5 {
			break
		}
		count++
		syncReq := &shop_business.SearchSyncShopRequest{
			ShopId:   0,
			PageSize: int64(shopSearchSyncPageSize),
			PageNum:  int64(shopSearchSyncPageNum),
		}
		shopSearchSyncPageNum++
		syncRsp, rspErr := client.SearchSyncShop(ctx, syncReq)
		if rspErr != nil {
			kelvins.ErrLogger.Errorf(ctx, "StoreShopTask %v,err: %v", serverName, rspErr)
			return
		}
		if syncRsp.Common.Code != shop_business.RetCode_SUCCESS {
			kelvins.ErrLogger.Errorf(ctx, "StoreShopTask req: %v, rsp: %v", json.MarshalToStringNoError(syncReq), json.MarshalToStringNoError(syncRsp))
			return
		}
		if syncRsp.List == nil || len(syncRsp.List) == 0 {
			break
		}
		storeShopInfo(ctx, syncRsp.List)
	}
}

func storeShopInfo(ctx context.Context, req []*shop_business.SearchSyncShopEntry) {
	for i := 0; i < len(req); i++ {
		storeShopInfoOne(ctx, req[i])
	}
}

func storeShopInfoOne(ctx context.Context, req *shop_business.SearchSyncShopEntry) {
	store := elasticsearch.SearchStoreShop{
		ShopId:       req.ShopId,
		NickName:     req.NickName,
		FullName:     req.FullName,
		ShopCode:     req.ShopCode,
		RegisterAddr: req.RegisterAddr,
		BusinessAddr: req.BusinessAddr,
		BusinessDesc: req.BusinessDesc,
	}
	body := json.MarshalToStringNoError(store)
	retCode := repository.SearchStore(ctx, elasticsearch.ESIndexShop, strconv.Itoa(int(req.ShopId)), body)
	if retCode != code.Success {
		kelvins.BusinessLogger.Infof(ctx, "storeShopInfoOne req：%v store retCode: %v", json.MarshalToStringNoError(req), errcode.GetErrMsg(retCode))
	}
}
